package com.xmlt.core.template;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.xmlt.core.template.tags.TemplateSectionElement;
import com.xmlt.core.template.tags.TemplateSectionElementFactory;

public class Utils {
	private static XPath _XPATH = null;

	public static XPathExpression getXpathExpression(String xpathStr)
			throws XPathExpressionException {
		if (_XPATH == null) {
			_XPATH = XPathFactory.newInstance().newXPath();
		}
		return _XPATH.compile(xpathStr);
	}

	public static NodeList evaluateXPath(Node n, String xpathExpr)
			throws XPathExpressionException {
		return (NodeList) getXpathExpression(xpathExpr).evaluate(n,
				XPathConstants.NODESET);
	}

	public static List<TemplateSectionElement> parseBody(Node n) throws TemplateException {
		List<TemplateSectionElement> elements = new ArrayList<TemplateSectionElement>();
		if (n == null)
			return elements;
		
		
		NodeList nl = n.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			TemplateSectionElement tse = TemplateSectionElementFactory
					.getTemplateSectionElement(nl.item(i));
			if (tse != null)
				elements.add(tse);
		}
		return elements;
	}

	public static String printNode(Node n) {
		try {
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			StringWriter sw = new StringWriter();
			xformer.transform(new DOMSource(n), new StreamResult(sw));
			return sw.toString();
		} catch (TransformerConfigurationException e) {
			//e.printStackTrace();
		} catch (TransformerException e) {
			//e.printStackTrace();
		}
		return "";
	}
}
